package com.designpatterns.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;

public class YMLUtil {

    //存储配置属性的Map集合
    public static Map<String, Object> conf = Maps.newHashMap();

    public static Object getValue(String path, String key) {
        //从classpath下获取配置文件路径
        Yaml yaml = new Yaml();
        //通过yaml对象将配置文件的输入流转换成map原始map对象
        Map map;
        try {
            map = yaml.loadAs(new FileInputStream(path), Map.class);
            //递归map对象将配置加载到conf对象中
            loadRecursion(map, "");
            return conf.get(key);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    //递归解析map对象
    public static void loadRecursion(Map<String, Object> map, String key) {
        map.forEach((k, v) -> {
            if (isParent(v)) {
                Map<String, Object> nextValue = (Map<String, Object>) v;
                loadRecursion(nextValue, (("".equals(key) ? "" : key + ".") + k));
            } else {
                if (StrUtil.isNotBlank(key)) {
                    conf.put(key + "." + k, v);
                } else {
                    conf.put(k, v);
                }

            }
        });
    }

    //判断是否还有子节点
    public static boolean isParent(Object o) {
        if (!(o instanceof String || o instanceof Character || o instanceof Byte)) {
            try {
                Number n = (Number) o;
            } catch (Exception e) {
                return true;
            }
        }
        return false;
    }
}
